import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/utils/PgyerService.dart';
import 'PgyerResponse/AppCheckResponse.dart';

class PgyerUpgradeHelper {
  /// 获取App详细信息
  static String appViewPath = "/apiv2/app/view";
  /// 安装App
  static String appInstallPath =  "/apiv2/app/install";
  /// 检测App是否有更新
  static String appCheckPath = "/apiv2/app/check";

  /// API - 检测App是否有更新
  static Future<AppCheckResponse?> appCheck(String buildVersion) async {
    var res = await PgyerService.post(appCheckPath, {
      "buildVersion": buildVersion
    }, {});
    if(res.data["code"] == 0) {
      return AppCheckResponse()..fromJson(res.data["data"] as Map<String, dynamic>);
    }
    return null;
  }
  /// API - 检测本地App的包信息
  static Future<PackageInfo> get packageInfo async {
    return await PackageInfo.fromPlatform();
  }

  /// 检测更新信息
  static Future<AppCheckResponse?> checkUpgrade({
    bool showLoading = false,
    bool showToast = false
  }) async {
    AppCheckResponse? response;
    var loading = showLoading ? showOverlayLoading(title: "正在检测更新") : null;
    try {
      var info = await packageInfo;
      var res = await appCheck(info.version);
      if(info.version != res?.buildVersion) {
        response = res;
        if(showToast) showOverlayToast("已检测到最新版本v${res!.buildVersion!}可以更新");
      } else {
        if(showToast) showOverlayToast("已经是最新版本了");
      }
    } catch (e) {
      if(showToast) showOverlayToast("检测异常，请重新检测");
    }
    loading?.remove();
    return response;
  }
  
  /// 是否需要提示用户升级
  static Future<bool> showUpgradeConfirmDialog(AppCheckResponse upgradeInfo) async {
    int index = await showOverlayConfirm(
      showClose: upgradeInfo.needForceUpdate != true,
      title: "有新版本v${upgradeInfo.buildVersion}可更新",
      child: Text(upgradeInfo.buildUpdateDescription ?? "修复了若干已知的问题", style: TextStyle(color: Colors.black54, fontSize: 14.dp),),
      actions: [
        OverlayConfirmAction(text: "升级版本", type: OverlayConfirmActionType.OK),
          upgradeInfo.needForceUpdate! ? null : OverlayConfirmAction(text: "取消", type: OverlayConfirmActionType.CANCEL),
      ].where((item)=> item != null).map((e)=> e!).toList()
    );
    return index == 0;
  }
}